package com.asktgapp.user.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.Html;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import com.asktgapp.JGTool.EmojiFilter;
import com.asktgapp.JGTool.JGColor;
import com.asktgapp.JGTool.Utils;
import com.asktgapp.R;
import com.asktgapp.application.ApiUtil;
import com.asktgapp.application.Apiservice;
import com.asktgapp.application.MyApplication;
import com.asktgapp.architecture.retrofit.ApiException;
import com.asktgapp.architecture.retrofit.ApiResponseBody;
import com.asktgapp.architecture.rxjava.ExceptionHandle;
import com.asktgapp.base.BaseFragment;
import com.asktgapp.engineer.activity.QuestionActivity;
import com.asktgapp.model.CollectionVO;
import com.asktgapp.model.FreeAskSearchVO;
import com.asktgapp.modulebase.ServiceUtil;
import com.asktgapp.modulebase.common.adapter.BaseAdapter;
import com.asktgapp.modulebase.common.adapter.BaseViewHolder;
import com.asktgapp.modulebase.common.util.PreferencesUtil;
import com.asktgapp.user.activity.AskDetialActivity;
import com.asktgapp.user.activity.EngineerListActivity;
import com.asktgapp.user.activity.FreeAskAnswerDetailActivity;
import com.asktgapp.user.activity.FreeAskPutQuestionsActivity;
import com.yanzhenjie.recyclerview.swipe.widget.DefaultItemDecoration;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * time:2018/1/24
 * Create By ZhaoKai
 * Email: dczk@foxmail.com
 * Description:快速提问检索问题页面
 */

public class FreeAskSearchFragment extends BaseFragment {
    private EditText tvSearch;
    private TextView tvDelete, myBack, tvNoData;
    private RecyclerView recycleHot;
    private BaseAdapter mBaseAdapter;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.fragment_free_ask_search, container, false);
        return super.onCreateView(inflater, viewGroup, savedInstanceState);
    }

    @Override
    protected void initView(View rootView) {
        getBaseActivity().getToolbar().setVisibility(View.GONE);
        tvSearch = rootView.findViewById(R.id.tvSearch);
        myBack = rootView.findViewById(R.id.myBack);
        tvDelete = rootView.findViewById(R.id.tvDelete);
        tvNoData = rootView.findViewById(R.id.tvNoData);
        tvNoData.setText( Html.fromHtml("没有检索到相关问题，请去"+ "<font color=\"#FD3722\"> 【快速提问】 </font>"));
        myBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getBaseActivity().onBackPressed();
            }
        });
        tvSearch.setFilters(new InputFilter[]{new EmojiFilter()});
        tvNoData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (checkIsLogin("登录后可查看更多内容"))
                    getActivity().startActivity(new Intent(getActivity(), EngineerListActivity.class));
            }
        });
        tvSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0) {
                    tvDelete.setVisibility(View.VISIBLE);
                    if (!Utils.noContainsEmoji(s.toString())) {
                        showTost("不支持输入emoji表情", 1);
                        return;
                    }
                    selLikeProbleList(s.toString());

                } else {
                    tvDelete.setVisibility(View.INVISIBLE);
                }
            }
        });

        tvDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tvSearch.setText("");
                tvDelete.setVisibility(View.INVISIBLE);
            }
        });

        recycleHot = rootView.findViewById(R.id.recycleHot);
        recycleHot.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        recycleHot.setNestedScrollingEnabled(false);
        recycleHot.addItemDecoration(new DefaultItemDecoration(JGColor.APP_BACKGROUND));

        mBaseAdapter = new BaseAdapter(getActivity()) {
            @Override
            public BaseViewHolder getViewHolder(ViewGroup parent, int viewType) {
                BaseViewHolder holder = new BaseViewHolder(LayoutInflater.from(getActivity()).inflate(R.layout.item_free_ask_search, parent, false),
                        new BaseViewHolder.Callbacks() {
                            @Override
                            public void bind(BaseViewHolder holder, Object data) {

                                if (data instanceof FreeAskSearchVO) {
                                    FreeAskSearchVO bean = (FreeAskSearchVO) data;
                                    String redText = "<font color=\"#FD3722\">" + searchText + "</font>";
                                    String content = bean.getContent();
                                    content=content.replaceAll(searchText, redText);
                                    holder.setText(R.id.tvName, Html.fromHtml(content));
                                }
                            }

                            @Override
                            public void onItemClick(View view, int position) {
                                FreeAskSearchVO bean = (FreeAskSearchVO) mBaseAdapter.getData().get(position);
                                FreeAskAnswerDetailActivity.startFreeAskAnswerDetailActivty( String.valueOf(bean.getId()),getContext());
//                                showTost("点击item", 0);
//                                CollectionVO bean = (CollectionVO) mBaseAdapter.getData().get(position);
//                                Intent intent = new Intent(getActivity(), IndustryInfoDetailActivity.class);
//                                intent.putExtra("id", bean.getId());
//                                startActivity(intent);
                            }
                        });


                return holder;
            }
        };
        recycleHot.setAdapter(mBaseAdapter);


    }

    @Override
    public void loadData() {

    }
    String searchText ;
    private void selLikeProbleList(String content) {
        //                    deviceId	string	是
//                    platform	int	是
//                    page	int	是
//                    content	string	否	搜索的文字
        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        searchText = content;
        ApiUtil.putDefultData(getActivity(), params);
        params.put("content", content);
        params.put("platform", "0");
        params.put("deviceId", Utils.getDeviceId(MyApplication.getInstance()));
        params.put("page", 1);
        showProgress(getClass().getSimpleName());
        Call<ApiResponseBody<List<FreeAskSearchVO>>> call = apiservice.selLikeProbleList(params);
        call.enqueue(new Callback<ApiResponseBody<List<FreeAskSearchVO>>>() {
            @Override
            public void onResponse(Call<ApiResponseBody<List<FreeAskSearchVO>>> call, Response<ApiResponseBody<List<FreeAskSearchVO>>> response) {
                dismissProgress();
                if (response.isSuccessful()) {
                    List<FreeAskSearchVO> bean = response.body().getResult();
                    if (bean != null && bean.size() > 0) {
                        tvNoData.setVisibility(View.GONE);
                        mBaseAdapter.setData(bean);
                    } else {
                        tvNoData.setVisibility(View.VISIBLE);
                    }
                } else {
                    showTost(response.raw().message(), 1);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody<List<FreeAskSearchVO>>> call, Throwable t) {
                dismissProgress();
                ApiException apiException = ExceptionHandle.handleException(t);
                if (apiException.isTokenInvalid()) {
                    showUnLoginSnackbar();
                } else if (apiException.isNetConnected()) {
                    showSetNetworkSnackbar();
                } else {
                    showTost(apiException.getMessage(), 0);
                }
            }
        });
    }

}
